<script lang="ts" setup>
import TitleBar from '@renderer/components/TitleBar.vue'
import UserListItem from '@renderer/components/UserListItem.vue'
import { onMounted, ref } from 'vue'
import { requestPost } from '@renderer/utils/commonRequest'
import { UserInterface } from '@renderer/types'

const userInfo = ref<UserInterface | undefined>()
const userList = ref<UserInterface[]>([])
const searchValue = ref<string>('')

onMounted(() => {
  userInfo.value = localStorage.getItem('userInfo')
    ? JSON.parse(localStorage.getItem('userInfo')!)
    : null
})

const onSearch = async (): Promise<void> => {
  if (!searchValue.value) {
    userList.value = []
    return
  }
  const data = await requestPost<UserInterface[]>('/user', {
    search: searchValue.value
  })
  if (!data) return
  userList.value = data.filter((item) => {
    if (item.id != userInfo.value?.id) return item
    return
  })
}

const addFriend = async (addUserId: string): Promise<void> => {
  const data = await requestPost<boolean>('/friendApplication/addFriend', {
    userId: userInfo.value?.id,
    addFriendUserId: addUserId,
    state: 0
  })
  if (!data) return
}
</script>

<template>
  <div class="agreeFriend">
    <TitleBar></TitleBar>
    <div class="search_box">
      <n-input
        v-model:value="searchValue"
        placeholder="请输入邮箱......."
        :bordered="false"
        @input="onSearch"
      >
      </n-input>
    </div>
    <div v-if="userList.length" class="context">
      <UserListItem
        v-for="item in userList"
        :key="item.id"
        :url="item.headPhoto"
        :cet-name="item.cetName"
      >
        <template #suffix>
          <n-button type="success" @click="addFriend(item.id)">添加 </n-button>
        </template>
      </UserListItem>
    </div>
    <div v-else class="context center">
      <n-empty description="暂无数据"> </n-empty>
    </div>
  </div>
</template>

<style scoped lang="less">
.agreeFriend {
  height: 100%;
  .search_box {
    height: 50px;
    margin-top: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 5%;
    .n-input {
      -webkit-app-region: no-drag;
      background-color: #e2e2e2;
      border: none !important;
    }
  }
  .context {
    height: calc(100% - 90px);
    background-color: #e6e6e7;
  }
  .center {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
